package com.oktest.measure.media.image

/**
 * @Author hhh
 * @Date 2020/10/25
 */
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.provider.MediaStore
import android.util.AttributeSet
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.FrameLayout
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cali.common.kt.uuid
import com.chad.library.adapter.base.BaseBinderAdapter
import com.oktest.measure.R
import com.oktest.measure.kt.showBigImage
import com.oktest.measure.media.image.adapter.ImageItem
import com.oktest.measure.media.image.adapter.PhotoBinder
import com.oktest.measure.media.image.adapter.TakePhotoBinder
import com.oktest.measure.media.image.adapter.TakePhotoItem
import java.io.File

class ImageGridView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    FrameLayout(context, attrs, defStyleAttr) {
    constructor(context: Context) : this(context, null, 0)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    private val recyclerView by lazy {
        RecyclerView(context)
    }
    private val imageAdapter by lazy {
        BaseBinderAdapter()
    }

    companion object {
        const val REQUEST_CAMERA_CODE = 1001
    }

    private var currentImagePath = ""

    init {
        val params = LayoutParams(MATCH_PARENT, WRAP_CONTENT)
        params.setMargins(8, 8, 8, 8)
        this.addView(recyclerView, params)
        imageAdapter.addItemBinder(PhotoBinder())
            .addItemBinder(TakePhotoBinder())
            .addChildClickViewIds(R.id.ivClose)
        recyclerView.apply {
            layoutManager = GridLayoutManager(context, 3)
            adapter = imageAdapter
        }
        imageAdapter.addData(TakePhotoItem())
        imageAdapter.setOnItemClickListener { adapter, view, position ->
            val item = imageAdapter.getItem(position)
            when (item) {
                is TakePhotoItem -> {
                    // 拍照
                    currentImagePath = "${uuid()}.jpg"
                    val imageFile = File(context.filesDir, currentImagePath)
                    val imageUri = FileProvider.getUriForFile(
                        context,
                        context.packageName + ".fileProvider",
                        imageFile
                    )
                    val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
                    context as Activity
                    context.startActivityForResult(intent, REQUEST_CAMERA_CODE)
                }
                is ImageItem -> {
                    // 展示大图
                    showBigImage(context, getImagePath(), position)
                }
            }
        }
        imageAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.ivClose) {
                imageAdapter.removeAt(position)
                if (imageAdapter.data.size == 4 && imageAdapter.data.last() !is TakePhotoItem) {
                    // 增加添加按钮
                    imageAdapter.addData(TakePhotoItem())
                }
            }
        }
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Bundle?) {
        if (requestCode == REQUEST_CAMERA_CODE) {
            val options = BitmapFactory.Options()
            options.inSampleSize = 2
            val filePath = File(context.filesDir, currentImagePath).absolutePath
            val bitmap = BitmapFactory.decodeFile(filePath, options)
            val imageItem = ImageItem(bitmap, filePath)
            imageAdapter.addData(imageAdapter.data.size - 1, imageItem)
            if (imageAdapter.data.size == 6) {
                // 移除添加按钮
                imageAdapter.removeAt(imageAdapter.data.size - 1)
            }
        }
    }

    fun getImagePath(): List<String> {
        return imageAdapter.data.filterIsInstance<ImageItem>().map {
            it.path
        }
    }

    fun clear() {
        imageAdapter.data.clear()
        imageAdapter.notifyDataSetChanged()
    }
}